package com.corgi.formatter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @title: FormatterAutoConfiguration
 * @description: Formatter 自动装配
 * @author: dengmiao
 * @create: 2019-10-10 14:15
 **/
@Configuration
@ConditionalOnProperty(prefix = "formatter", name = "enabled", havingValue = "true",
		matchIfMissing = true) // 当属性配置不存在时，同样视作匹配
@ConditionalOnResource(resources = "META-INF/spring.factories")
@ConditionalOnNotWebApplication
@ConditionalOnExpression("${formatter.enabled:true}")
public class FormatterAutoConfiguration {

	/**
	 * 构建 {@link DefaultFormatter} Bean
	 * @return {@link DefaultFormatter}
	 */
	@Bean
	@ConditionalOnMissingClass(value = "com.fasterxml.jackson.databind.ObjectMapper")
	public Formatter defaultFormatter() {
		return new DefaultFormatter();
	}

	/**
	 * JSON 格式 {@link Formatter} Bean
	 * @return {@link JsonFormatter}
	 */
	@Bean
	@ConditionalOnClass(name = "com.fasterxml.jackson.databind.ObjectMapper")
	@ConditionalOnMissingBean(type = "com.fasterxml.jackson.databind.ObjectMapper")
	public Formatter jsonFormatter() {
		return new JsonFormatter();
	}

	@Bean
	@ConditionalOnBean(ObjectMapper.class)
	public Formatter objectMapperFormatter(ObjectMapper objectMapper) {
		return new JsonFormatter(objectMapper);
	}

	@Bean
	public ObjectMapper objectMapper() {
		return new ObjectMapper();
	}
}
